package service;

import dao.UserDao;
import entity.User;
import util.JwtUtil;
import util.ResponseUtil;
import util.ValidationUtil;
import util.EntityConverter;
import util.FileStorageUtil;
import java.sql.SQLException;
import java.util.Map;
import java.util.HashMap;
import org.mindrot.jbcrypt.BCrypt;
import java.io.IOException;

public class UserService {
    private final UserDao userDao;

    public UserService() {
        this.userDao = new UserDao();
    }
    
    // 用户注册
    public Map<String, Object> register(String username, String password, String contentType, String requestBody) {
        try {
            // 参数验证
            ValidationUtil.validateUsername(username);
            ValidationUtil.validatePassword(password);
            
            // 检查用户名是否存在
            if (userDao.findByUsername(username.trim()) != null) {
                return ResponseUtil.error("用户名已存在");
            }
            
            // 创建用户 - 加密密码
            String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
            User user = new User();
            user.setUsername(username.trim());
            user.setPassword(hashedPassword); // 存储加密后的密码
            user = userDao.create(user);
            
            // 生成token
            String token = JwtUtil.generateToken(user.getUserId(), user.getUsername());
            
            // 返回结果
            Map<String, Object> userInfo = EntityConverter.userToBasicMap(user);
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", userInfo);
            return ResponseUtil.success("注册成功", data);
            
        } catch (SQLException e) {
            System.out.println("注册异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseUtil.error("服务器错误");
        }
    }
    
    // 用户登录
    public Map<String, Object> login(String username, String password, String requestBody) {
        try {
            // 查找用户并验证密码
            User user = userDao.findByUsername(username.trim());
            if (user == null || !BCrypt.checkpw(password, user.getPassword())) {
                return ResponseUtil.error("用户名或密码错误");
            }
            
            // 生成token
            String token = JwtUtil.generateToken(user.getUserId(), user.getUsername());
            
            // 返回结果
            Map<String, Object> userInfo = EntityConverter.userToBasicMap(user);
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", userInfo);
            return ResponseUtil.success("登录成功", data);
            
        } catch (SQLException e) {
            System.out.println("登录异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseUtil.error("服务器错误");
        }
    }
    
    // 获取用户信息
    public Map<String, Object> getUserInfo(String token) {
        try {
            System.out.println("=== 获取用户信息 ===");
            System.out.println("Token: " + token);
            
            // token验证
            if (token == null || token.isEmpty()) {
                return ResponseUtil.unauthorized();
            }
            
            // Bearer前缀检查
            if (!token.startsWith("Bearer ")) {
                return ResponseUtil.unauthorized();
            }
            
            // 解析token
            token = token.substring(7);
            Long userId;
            try {
                userId = JwtUtil.getUserIdFromToken(token);
            } catch (Exception e) {
                return ResponseUtil.error("登录已过期");
            }
            
            User user = userDao.findById(userId);
            if (user == null) {
                return ResponseUtil.error("用户不存在");
            }
            
            return ResponseUtil.success(EntityConverter.userToMap(user));
            
        } catch (SQLException e) {
            System.out.println("获取用户信息异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseUtil.error("服务器错误");
        }
    }
    
    // 更新用户背景图片
    public Map<String, Object> updateBackgroundImage(Long userId, String backgroundImage, 
            String contentType, long fileSize, boolean fileExists) {
        try {
            // 检查文件是否存在
            if (!fileExists) {
                return ResponseUtil.error("请选择要上传的图片");
            }
            
            // 验证文件类型
            if (contentType == null || !contentType.startsWith("image/")) {
                return ResponseUtil.error("只能上传图片文件");
            }
            
            // 验证文件大小（5MB）
            if (fileSize > 5 * 1024 * 1024) {
                return ResponseUtil.error("封面图片大小不能超过5MB");
            }
            
            // 获取用户当前的背景图片路径
            User currentUser = userDao.findById(userId);
            String oldBackgroundImage = currentUser != null ? currentUser.getBackgroundImage() : null;
            
            // 更新数据库中的背景图片路径
            if (!userDao.updateBackgroundImage(userId, backgroundImage)) {
                return ResponseUtil.error("更新背景图片失败");
            }
            
            // 删除旧的背景图片文件
            try {
                if (oldBackgroundImage != null && !oldBackgroundImage.isEmpty()) {
                    FileStorageUtil.deleteFile(oldBackgroundImage);
                }
            } catch (IOException e) {
                System.out.println("删除旧背景图片失败: " + e.getMessage());
                // 继续执行，不影响更新操作
            }
            
            User user = userDao.findById(userId);
            Map<String, Object> data = new HashMap<>();
            data.put("backgroundUrl", user.getBackgroundImage());
            return ResponseUtil.success("更新成功", data);
            
        } catch (SQLException e) {
            System.out.println("更新背景图片异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseUtil.error("服务器错误");
        }
    }

    // 更新用户背景色
    public Map<String, Object> updateBackgroundColor(Long userId, String backgroundColor) {
        try {
            // 验证颜色格式
            ValidationUtil.validateColorCode(backgroundColor);

            if (!userDao.updateBackgroundColor(userId, backgroundColor)) {
                return ResponseUtil.error("更新失败");
            }
            
            return ResponseUtil.success("背景色更新成功");
            
        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseUtil.error("服务器错误");
        }
    }
}